package com.shadow.baiqun.delegate.room.check;

import android.device.ScanDevice;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.config.ItemField;
import com.shadow.baiqun.delegate.room.adapter.CheckTaskDetailAdapter;
import com.shadow.baiqun.event.RefreshCheckTaskDetailEvent;
import com.shadow.baiqun.event.RefreshCheckTaskEvent;
import com.shadow.baiqun.event.ScanInfoEvent;
import com.shadow.baiqun.view.TableHeadView;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.recycler.BaseDecoration;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author zhangyu
 * @date 2018/7/13
 */

public class CheckDetailDelegate extends RxShadowDelegate {
    private static final String TASK_ID = "taskId";

    public static CheckDetailDelegate create(String taskId) {
        final CheckDetailDelegate contentDelegate = new CheckDetailDelegate();
        final Bundle bundle = new Bundle();
        bundle.putString(TASK_ID, taskId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.lv_title)
    TableHeadView mHeadView;
    private CheckTaskDetailAdapter mTaskDetailAdapter;
    private boolean isRequesting = false;
    private String mTaskId;
    private ScanDevice mScanDevice;
    private static final int PAGE_SIZE = 50;
    private int mNextRequestPage = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mTaskId = bundle.getString(TASK_ID);
        }
        mScanDevice = new ScanDevice();
        //广播输出
        mScanDevice.setOutScanMode(0);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_check_detail;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(new RefreshCheckTaskEvent());
                    pop();
                }
            });
            mToolbar.setTitle("检测任务详情");
            mToolbar.inflateMenu(R.menu.scan);
            mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    int i = item.getItemId();
                    if (i == R.id.menu_scan) {
                        scan();
                    }
                    return true;
                }
            });
        }
        List<String> list = new ArrayList<>();
        list.add("零件编号");
        list.add("零件数量");
        list.add("库位");
        list.add("状态");
        mHeadView.setHeaders(list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources()
                .getColor(R.color.color_white_light_gray), 1));
        mTaskDetailAdapter = new CheckTaskDetailAdapter(getContext(),
                R.layout.item_room_check_detail_task, null);
        mTaskDetailAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);
        mTaskDetailAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
        if (mTaskDetailAdapter.getEmptyView() != null) {
            mTaskDetailAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
        mRecyclerView.setAdapter(mTaskDetailAdapter);
    }

    private void loadMore() {
        requestData(false);
    }

    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mTaskDetailAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe()
    public void scanEvent(ScanInfoEvent event) {
        requestBoardCodeInfoFromServer(event.mInfo);
    }

    @Subscribe
    public void CheckDetailRefresh(RefreshCheckTaskDetailEvent event) {
        refresh();
    }

    private void requestBoardCodeInfoFromServer(final String boardCode) {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/indoorTest/getPartsByTabnum")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        BoardCodeDataConverter converter = new BoardCodeDataConverter();
                        BoardInfoEntity boardInfoEntity = converter.convert(response);
                        if (boardInfoEntity != null) {
                            List<MultipleItemEntity> list = mTaskDetailAdapter.getData();
                            boolean has = false;
                            for (MultipleItemEntity itemEntity : list) {
                                CheckDetailEntity entity = itemEntity.getField(ItemField.ITEM_OBJ);
                                if (entity.getTagId().equals(boardInfoEntity.getTabId())) {
                                    has = true;
                                    boardInfoEntity.setPartCount(Integer.parseInt(entity.getPartsTotalnum()));
                                    boardInfoEntity.setId(entity.getId());
                                    boardInfoEntity.setGoodCount(entity.getStockNum());
                                    start(CheckTaskCommitDelegate.create(boardInfoEntity));
                                    break;
                                }
                            }
                            if (!has) {
                                ToastUtils.showToast(getContext(), "未匹配到该标签的相关信息!");
                            }

                        } else {
                            ToastUtils.showToast(getContext(), "条码号无效!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), "未找到相关信息!");
                    }
                })
                .params("tabnum", boardCode)
                .build()
                .unRestGet());
    }

    private void requestData(final boolean isRefresh) {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/indoorTest/detileList")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mTaskDetailAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        CheckDetailDataConverter converter = new CheckDetailDataConverter();
                        converter.setJsonData(response);
                        setData(isRefresh, converter.convert());
                        isRequesting = false;
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mTaskDetailAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                    }
                })
                .params("taskid", mTaskId)
                .params("pageNum", mNextRequestPage)
                .params("pageSize", PAGE_SIZE)
                .build()
                .unRestGet());
    }

    private void setData(boolean isRefresh, List<MultipleItemEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mTaskDetailAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mTaskDetailAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mTaskDetailAdapter.loadMoreEnd(isRefresh);
        } else {
            mTaskDetailAdapter.loadMoreComplete();
        }
    }

    private void scan() {
        if (!mScanDevice.isScanOpened()) {
            mScanDevice.openScan();
        }
        mScanDevice.startScan();
        // requestBoardCodeInfoFromServer("000000032715");
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refresh();
    }
}
